#include "main.h"
#include "bsp.h"

/*考虑到需要更改地址，因此需要使用双向传输的模式*/
#define TX_MODE		0
#define RX_MODE  	0
#define DOUBLE_MODE  1

#define PEDAL  1
#define MASTER  0

uint8_t tx_buf[32] = {0};
uint8_t rx_buf[32] = {0};

uint8_t state_flag;
uint8_t flag_1s;
uint8_t flag_200ms;
uint8_t flag_1ms;
uint8_t test_main_1 = 0;
uint8_t ssc_flag = 0;//self_start check(1:success 0:failed)
uint8_t ssc_flag_count = 0;//check enter self_start check count
uint8_t state_tx_flag = 0;
RCC_ClocksTypeDef RCC_Clocks;


int main(void)
{
	RCC_GetClocksFreq(&RCC_Clocks);
	CONFIGURE_TIMER3_Init();
	CONFIGURE_TIMER14_Init();
	CONFIGURE_GPIO_Init();
	CONFIGURE_ADC_Init();
	CONFIGRURE_DMA_Init();
	
	SI24R1_Init();
	while(SI24R1_Check());

	while(1)
	{
		//进行dma的数据采样
		if(flag_1ms == 1)
		{
			flag_1ms = 0;
			test_main_1 ++;
			
		}
		
		
		if(ssc_flag == 0)
		{
			if(flag_1s == 1)
			{
				flag_1s = 0;
				if(SI24R1_Check() == 0)    ssc_flag = 1;
				ssc_flag_count ++;
			}
		}
		if(ssc_flag == 1)
		{
			#if TX_MODE
			if(flag_200ms == 1)
			{
				flag_200ms = 0;
				test_main_1 ++;
				tx_buf[0] += 1;
				tx_buf[1] += 2;
				tx_package(tx_buf);//
			}
			#endif
			
			#if RX_MODE
			if(flag_200ms == 1)
			{
				flag_200ms = 0;
				test_main_1 ++;
				SI24R1_RX_Mode();
				SI24R1_RxPacket(rx_buf);
			}
			#endif
			
			#if DOUBLE_MODE
			#if PEDAL
			static uint8_t value_default = 0;//0:表示初始为发送测，1：表示初始为接收测
			static uint8_t start_state = 0;
			#endif
			#if MASTER
			static uint8_t value_default = 1;//0:表示初始为发送测，1：表示初始为接收测
			static uint8_t start_state = 1;
			#endif
			uint8_t tx_res = 3;
			uint8_t rx_res = 3;
			static uint8_t pedal_delay_count = 0;//脚踏侧如果接收数据一直失败，则回到最初的发送模式
			static uint8_t master_delay_count = 0;//主机侧如果发送数据一直失败，则回到最初的接收模式
			if(flag_200ms == 1)
			{
				flag_200ms = 0;
				if(value_default == 0)
				{
					tx_buf[0] += 1;
					tx_buf[1] += 2;
					tx_res = tx_package(tx_buf);
				}
				if(value_default == 1)
				{
					SI24R1_RX_Mode();
					rx_res = SI24R1_RxPacket(rx_buf);
				}				
				if(tx_res == 0x20)//表示发送成功，此时切换状态
				{
					value_default = 1;
					pedal_delay_count = 0; //在脚踏侧如果发送成功，则接收失败的延时计数清0
				}
				else//没有发送成功进入这里，进行计数延时，如果初始状态是发送侧，则继续保持发送侧,如果是接收侧，则继续保持接收
				{
					master_delay_count ++;
					if(master_delay_count >= 3)
					{
						value_default = start_state;//回到最初的状态
					}
				}
				if(rx_res == 0x00)//表示接收成功，此时切换状态
				{
					value_default = 0;
					master_delay_count = 0;
				}
				else//没有接收成功，进行计数延时，和上述保持一致，
				{
					pedal_delay_count ++;
					if(pedal_delay_count >3)
					{
						value_default = start_state;//回到最初的状态
					}
				}
			}
			
			#endif
			
		}
		
		
		
	}
}
